<!--管理员主页--房源管理一栏内容-->
<template>
  <div class="admin-house-container">
    <h2>房源管理</h2>

    <!-- 搜索和筛选区域 -->
    <div class="filter-container">
      <el-input v-model="searchQuery" placeholder="搜索房源标题" class="search-input" clearable @clear="handleSearch"
        @keyup.enter="handleSearch">
        <template #append>
          <el-button @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
          </el-button>
        </template>
      </el-input>

      <el-input v-model="landlordNameFilter" placeholder="搜索房东名称" class="search-input" clearable @clear="handleSearch"
        @keyup.enter="handleSearch">
        <template #append>
          <el-button @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
          </el-button>
        </template>
      </el-input>

      <span class="filter-label">状态：</span>
      <el-select v-model="statusFilter" placeholder="房源状态" @change="handleSearch" class="select-input">
        <el-option label="全部" :value="6" />
        <el-option label="待审核" :value="0" />
        <el-option label="已租" :value="1" />
        <el-option label="空置" :value="2" />
        <el-option label="维修中" :value="3" />
        <el-option label="审核未通过" :value="4" />
        <el-option label="违规" :value="5" />
      </el-select>
    </div>

    <!-- 房源列表表格 -->
    <el-table v-loading="loading" :data="houses" style="width: 100%; margin-top: 20px" border>
      <el-table-column prop="title" label="标题" min-width="150" show-overflow-tooltip />
      <el-table-column label="地址" min-width="180" show-overflow-tooltip>
        <template #default="{ row }">
          {{ formatAddress(row.address) }}
        </template>
      </el-table-column>
      <el-table-column prop="houseType" label="房型" width="100" />
      <el-table-column prop="area" label="面积(㎡)" width="100" />
      <el-table-column prop="price" label="月租(元)" width="100" />
      <el-table-column prop="deposit" label="押金(元)" width="100" />
      <el-table-column label="房东" width="120">
        <template #default="{ row }">
          <div class="landlord-info">
            <el-avatar :size="30"
              :src="row.landlord.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" />
            <span>{{ row.landlord.username }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <div class="action-buttons">
            <!-- 所有房源都有查看详情按钮 -->
            <el-button size="small" @click="viewHouseDetail(row)">查看详情</el-button>

            <!-- 待审核状态的房源有审核通过和不通过按钮 -->
            <template v-if="row.status === 0">
              <el-button size="small" type="success" @click="approveHouse(row)">通过</el-button>
              <el-button size="small" type="danger" @click="rejectHouse(row)">不通过</el-button>
            </template>

            <!-- 已租、空置和维修中状态的房源有违规操作按钮 -->
            <template v-if="[1, 2, 3].includes(row.status)">
              <el-button size="small" type="warning" @click="markAsViolation(row)">标记违规</el-button>
            </template>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper" :total="totalHouses" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>

    <!-- 房源详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" title="房源详情" width="50%" destroy-on-close>
      <div v-if="currentHouse" class="house-detail">
        <h3>{{ currentHouse.title }}</h3>

        <!-- 房源基本信息 -->
        <el-descriptions :column="2" border>
          <el-descriptions-item label="地址">{{ formatAddress(currentHouse.address) }}</el-descriptions-item>
          <el-descriptions-item label="房型">{{ currentHouse.houseType }}</el-descriptions-item>
          <el-descriptions-item label="面积">{{ currentHouse.area }}㎡</el-descriptions-item>
          <el-descriptions-item label="月租">{{ currentHouse.price }}元</el-descriptions-item>
          <el-descriptions-item label="押金">{{ currentHouse.deposit }}元</el-descriptions-item>
          <el-descriptions-item label="发布时间">{{ currentHouse.create_time }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ getStatusText(currentHouse.status) }}</el-descriptions-item>
        </el-descriptions>

        <!-- 房源图片 -->
        <div class="house-images" style="overflow: hidden;">
          <h4>房源图片</h4>
          <el-carousel :interval="4000" height="280px" v-show="currentHouse.images && currentHouse.images.length > 0">
            <el-carousel-item v-for="(image, index) in currentHouse.images" :key="index">
              <video v-if="isVideoFile(image)" controls autoplay loop muted class="carousel-item">
                <source :src="image" :type="getVideoType(image)">
                您的浏览器不支持视频播放。
              </video>
              <img v-else :src="image" alt="房源图片" class="carousel-item">
            </el-carousel-item>
          </el-carousel>
          <el-empty v-show="!currentHouse.images || currentHouse.images.length === 0" description="暂无图片" />
        </div>

        <!-- 房东信息 -->
        <div class="landlord-detail">
          <h4>房东信息</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="用户名">{{ currentHouse.landlord.username }}</el-descriptions-item>
            <el-descriptions-item label="性别">{{ currentHouse.landlord.gender === 1 ? '男' : currentHouse.landlord.gender
              ===
              2?'女':'保密' }}</el-descriptions-item>
            <el-descriptions-item label="年龄">{{ currentHouse.landlord.age || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ currentHouse.landlord.phone || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="电子邮箱">{{ currentHouse.landlord.email || '未知' }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 标签/关键词 -->
        <div class="house-keywords">
          <h4>房源标签</h4>
          <div class="keyword-list">
            <el-tag v-for="(keyword, index) in currentHouse.keywords" :key="index" class="keyword-tag">
              {{ keyword }}
            </el-tag>
            <el-empty v-if="!currentHouse.keywords || currentHouse.keywords.length === 0" description="暂无标签" />
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 审核不通过原因弹窗 -->
    <el-dialog v-model="rejectDialogVisible" title="审核不通过原因" width="30%">
      <el-form>
        <el-form-item label="不通过原因">
          <el-input v-model="rejectReason" type="textarea" rows="4" placeholder="请输入审核不通过的原因"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmReject">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 标记违规原因弹窗 -->
    <el-dialog v-model="violationDialogVisible" title="违规原因" width="30%">
      <el-form>
        <el-form-item label="违规原因">
          <el-input v-model="violationReason" type="textarea" rows="4" placeholder="请输入违规原因"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="violationDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmViolation">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import apiClient from '@/api/api'
import { House } from '@/utils/house'
import formatAddress from '@/utils/house'

// 状态数据
const houses = ref<House[]>([])
const loading = ref(true)
const currentPage = ref(1)
const pageSize = ref(10)
const totalHouses = ref(0)
// 搜索和筛选数据
const searchQuery = ref('') // 搜索的title
const statusFilter = ref(6) // 状态筛选
const landlordNameFilter = ref('') // 房东名称筛选

// 详情弹窗数据
const detailDialogVisible = ref(false)
const currentHouse = ref<House | null>(null)

// 审核不通过弹窗数据
// 审核不通过弹窗是否可见
const rejectDialogVisible = ref(false)
// 审核不通过原因
const rejectReason = ref('')
// 审核不通过的房源
const houseToReject = ref<House | null>(null)

// 违规弹窗数据
// 标记违规弹窗是否可见
const violationDialogVisible = ref(false)
// 违规原因
const violationReason = ref('')
//标记违规的房源
const houseToViolate = ref<House | null>(null)

// 获取房源列表
const fetchHouses = async () => {
  loading.value = true
  try {
    const res = await apiClient.get('/house/getHouseList', {
      params: {
        page: currentPage.value,
        size: pageSize.value,
        title: searchQuery.value,
        status: statusFilter.value,
        landlordName: landlordNameFilter.value
      }
    })
    if (res.data.code === 1) {
      houses.value = res.data.data.list
      totalHouses.value = res.data.data.total
    } else {
      ElMessage.error(res.data.message)
    }
    loading.value = false

  } catch (error) {
    console.error('获取房源列表失败:', error)
    ElMessage.error('获取房源列表失败')
    loading.value = false
  }
}
// 判断是否为视频文件
const isVideoFile = (url: string): boolean => {
    if (!url) return false
    const fileName = url.toLowerCase()
    return fileName.endsWith('.mp4') || fileName.endsWith('.webm') || 
           fileName.endsWith('.avi') || fileName.endsWith('.mov')
}

// 获取视频MIME类型
const getVideoType = (url: string): string => {
    if (!url) return ''
    const fileName = url.toLowerCase()
    if (fileName.endsWith('.mp4')) return 'video/mp4'
    if (fileName.endsWith('.webm')) return 'video/webm'
    if (fileName.endsWith('.avi')) return 'video/x-msvideo'
    if (fileName.endsWith('.mov')) return 'video/quicktime'
    return ''
}
// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchHouses()
}

// 分页大小变化处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchHouses()
}

// 当前页变化处理
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchHouses()
}

// 获取状态文本
const getStatusText = (status: number): string => {
  const statusMap: Record<number, string> = {
    0: '待审核',
    1: '已租',
    2: '空置',
    3: '维修中',
    4: '审核未通过',
    5: '违规'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态标签类型
const getStatusType = (status: number): string => {
  const typeMap: Record<number, string> = {
    0: 'info',     // 待审核 - 蓝色
    1: 'success',  // 已租 - 绿色
    2: '',         // 空置 - 默认灰色
    3: 'warning',  // 维修中 - 黄色
    4: 'danger',   // 审核未通过 - 红色
    5: 'danger'    // 违规 - 红色
  }
  return typeMap[status] || ''
}

// 查看房源详情
const viewHouseDetail = (house: House) => {
  currentHouse.value = house
  detailDialogVisible.value = true
}

// 审核通过
const approveHouse = async (house: House) => {
  try {
    await changeHouseStatus(house.id, 2)
  } catch (error) {
    console.error('审核通过失败:', error)
    ElMessage.error('审核通过失败')
  }
}

// 打开审核不通过弹窗
const rejectHouse = (house: House) => {
  houseToReject.value = house
  rejectReason.value = ''
  rejectDialogVisible.value = true
}

// 确认审核不通过
const confirmReject = async () => {
  if (!rejectReason.value.trim()) {
    ElMessage.warning('请输入审核不通过的原因')
    return
  }
  
  // 安全地检查houseToReject.value是否存在以及id是否存在
  if (!houseToReject.value || typeof houseToReject.value.id !== 'number') {
    ElMessage.error('房源信息无效')
    return
  }
  
  try {
    await changeHouseStatus(houseToReject.value.id, 4)
    rejectDialogVisible.value = false
  } catch (error) {
    console.error('审核不通过操作失败:', error)
    ElMessage.error('审核不通过操作失败')
  }
}

// 打开标记违规弹窗
const markAsViolation = (house: House) => {
  houseToViolate.value = house
  violationReason.value = ''
  violationDialogVisible.value = true
}

// 确认标记违规
const confirmViolation = async () => {
  if (!violationReason.value.trim()) {
    ElMessage.warning('请输入违规原因')
    return
  }

  // 安全地检查houseToViolate.value是否存在以及id是否存在
  if (!houseToViolate.value || typeof houseToViolate.value.id !== 'number') {
    ElMessage.error('房源信息无效')
    return
  }

  try {
    await changeHouseStatus(houseToViolate.value.id, 5)
    violationDialogVisible.value = false
  } catch (error) {
    console.error('标记违规操作失败:', error)
    ElMessage.error('标记违规操作失败')
  }
}
// 更改房屋状态
const changeHouseStatus = async (houseId: number, newStatus: number) => {
  try {
    await apiClient.put('/house/updateStatus', {
      id: houseId,
      status: newStatus,
    }).then(res => {
      if (res.data.code === 1) {
        ElMessage.success('操作成功')
        // 更新本地数据
        if (houseToReject.value) {
          const index = houses.value.findIndex(h => h.id === houseId)
          if (index !== -1) {
            houses.value[index].status = newStatus // 更新为审核未通过状态
          }
        }
        // 刷新页面
        fetchHouses()
      }else{
        ElMessage.error(res.data.message||'操作失败')
      }
    }) 
  }catch (error) {
    console.error('更改房屋状态失败:', error)
    ElMessage.error('操作失败')
  } 
}
// 组件挂载时获取房源列表
onMounted(async () => {
  document.title = '房源管理'
  await fetchHouses()
})
</script>

<style scoped>
.admin-house-container {
  padding: 20px;
}

.filter-container {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.search-input {
  width: 40%;
}
.filter-label {
  display: flex;
  align-items: center;
  margin-right: 5px;
  white-space: nowrap;
}
.select-input {
  width: 15%;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.landlord-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.house-detail {
  padding: 10px;
}

.house-detail h3 {
  margin-bottom: 20px;
  font-size: 20px;
  font-weight: bold;
}

.house-detail h4 {
  margin: 20px 0 10px;
  font-size: 16px;
  font-weight: bold;
}

.house-images {
  margin-top: 20px;
}

.carousel-item {
  width: 100%;
  height: 100%;
  object-fit: contain;
  background-color: #f5f5f5;
}

.landlord-detail {
  margin-top: 20px;
}

.house-keywords {
  margin-top: 20px;
}

.keyword-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.keyword-tag {
  margin-right: 5px;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .action-buttons {
    flex-direction: column;
    align-items: flex-start;
  }

  .action-buttons .el-button {
    margin-left: 0;
    margin-bottom: 5px;
  }
}

/* 弹窗位置调整 */
:deep(.el-dialog) {
  margin-top: 2vh !important;
}
</style>

// 在script部分添加
const handleMediaLoad = () => {
  // 触发一次window的resize事件，让轮播图重新计算尺寸
  window.dispatchEvent(new Event('resize'))
}